﻿package {
	import flash.display.*;
	import flash.events.*;
	import covert;
	import FramePlayer;
	public class Role extends Sprite {
		static var faces:Array = ['rightto','rightdownto','downto','leftdownto','leftto','leftupto','upto','rightupto','right','rightdown','down','leftdown','left','leftup','up','rightup'];
		static var faceto:Array = ['right','rightdown','down','leftdown','left','leftup','up','rightup'];
		static var facesfp:Array = [1,1,1,1,1,1,1,1,8,8,8,8,8,8,8,8];
		public var figure;
		var target:Array = [];
		var step:Number = 6;
		public var globalX:Number,globalY:Number;
		var pass = null;
		var emotion:Array;
		var action:Array;
		var dx:Number = 0,dy:Number = 0;
		var render:Boolean = false;
		public function Role(){
			figure = new FramePlayer();
			addChild(figure);
		}
		function frame(e){
			if (target.length == 0) {
				return;
			}else{
				var flag = target[0]();
				if(flag){
					removeEventListener(Event.ENTER_FRAME,frame);
					target.shift();
				}
			}
		}
		function moveto(targetX,targetY) {
			var cx:Number = targetX-globalX;
			var cy:Number = targetY-globalY;
			if(cx == 0 && cy == 0)return true;
			var a:Number = Math.atan2(cy, cx);
			dx = Math.cos(a)*step;
			dy = Math.sin(a)*step;
			figure.goto(direct(a));
			if (Math.abs(cx)<Math.abs(dx)) {
				dx = cx;
			}
			if (Math.abs(cy)<Math.abs(dy)) {
				dy = cy
			}
			pass(this);
		}
		function say(to,fun) {
			target.push({'act':'say','to':to,'fun':fun});
		}
		function clearTarget() {
			target = [];
			removeEventListener(Event.ENTER_FRAME,frame);
		}
		
		function setMoves(pic) {
			figure.addActions(Role.faces,Role.facesfp,pic,8,9,3);
		}
		function direct(a:Number):String{
			return faceto[int(((a + Math.PI*2.125)%(Math.PI*2))/ (Math.PI/4))];
		}
		function turn(tx,ty = undefined){
			var face;
			if(ty == undefined){
				if(tx is String){
					face = tx;
				}else{
					face = faceto[tx];
				}
			}else{
				var a:Number = Math.atan2(ty - y,tx - x);
				face = direct(a);
			}
			figure.goto(face);
		}	
		function addTarget(targetX,targetY){
			var t:Function = function(){
				return moveto(targetX,targetY);
			}
			clearTarget();
			addFunction(t);
		}
		function addFunction(fun){
			if(target.length == 0){
				target.push(fun);
				addEventListener(Event.ENTER_FRAME,frame);
			}else{
				target.push(fun);
			}
		}

	}
}